//$URL: http://dasding.googlecode.com/svn/branches/testzeugs/api/src/main/java/de/piratech/dasding/security/contextfilter/UserRoleContextFilter.java $
//$Id: UserRoleContextFilter.java 90 2012-11-20 18:42:49Z amuthmann@gmail.com $
package de.piratech.dasding.security.contextfilter;

import javax.ws.rs.ext.Provider;



import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import de.piratech.dasding.data.User;
import de.piratech.dasding.security.UserSecurityContext;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Filter which checks if a user has a given role.
 *
 * @author deveth0
 */
@Provider    // register as jersey's provider
public class UserRoleContextFilter implements ResourceFilter, ContainerRequestFilter {

  private User.USER_ROLE[] mRoles;

  public UserRoleContextFilter(User.USER_ROLE[] pRoles) {
    this.mRoles = pRoles;
  }

  @Override
  public ContainerRequest filter(ContainerRequest pRequest) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principle = authentication == null ? null : authentication.getPrincipal();
    if (principle != null && principle instanceof User) {
      User user = (User) principle;
      for (User.USER_ROLE role : mRoles) {
        if (user.hasRole(role)) {
          pRequest.setSecurityContext(new UserSecurityContext(user));
          return pRequest;
        }
      }
    }
    throw new WebApplicationException(Response.Status.FORBIDDEN);
  }

  @Override
  public ContainerRequestFilter getRequestFilter() {
    return this;
  }

  @Override
  public ContainerResponseFilter getResponseFilter() {
    return null;
  }
}